var express = require('express');
var router = express.Router();

const md5 = require('md5')

const moment = require('moment')
const AuthModel = require('../../models/AuthModel')

/* GET home page. */

router.get('/auth', function (req, res, next) {
  res.render('auth/reg')
})



router.post('/auth', function (req, res, next) {
  const { username, password } = req.body
  AuthModel.create({ username, password: md5(password) }, (err, data) => {
    if (err) {
      res.status(500).send('注册失败~~')
      return
    }
    res.render('success', {
      msg: '添加成功',
      url: '/login'
    })
  })
})

router.get('/login', function (req, res, next) {
  res.render('auth/login')
})

router.post('/login', function (req, res, next) {
  const { username, password } = req.body
  AuthModel.findOne({ username, password: md5(password) }, (err, data) => {
    if (err) {
      res.status(500).send('登录失败~~')
      return
    }
    if (data) {
      // Ensure session object exists before setting properties

      //写入session
      req.session.username = data.username;
      req.session._id = data._id;
      res.render('success', {
        msg: '登录成功',
        url: '/account'
      })
    } else {
      res.status(500).send('用户名或密码错误~~')
    }
  })
})

router.post('/logout', function (req, res, next) {
  req.session.destroy(function (err) {
    res.redirect('/login')
  })
})


module.exports = router;
